import java.io.InterruptedIOException;

//实现一个阻塞队列
class MyBlockingQueue {
    private String[] elems = null;
    //设置队头
    //head   表示第一个元素   tail表示最后一个元素的下一个元素
    private volatile int head = 0;
    private volatile int tail = 0;
    private volatile int size = 0;

    public MyBlockingQueue(int capacity) {
        elems = new String[capacity];
    }

    //进队列
    void put(String elem) throws InterruptedException {
        synchronized (this) {
            while (size >= elems.length) {
                //队列满了 ，要阻塞等待一下
                this.wait();
            }
            //把新的元素放到tail所在的位置上
            elems[tail] = elem;
            tail++;
            if (tail >= elems.length) {
                //到达末尾  就要回到开头
                tail = 0;
            }
            //更新size的值
            size++;

            //put成功一个就要唤醒take阻塞的wait
            this.notify();
        }
    }


    //取出队列中的元素
    String take() throws InterruptedException {
        synchronized (this) {
            while (size == 0) {
                //队列为空  说明没元素了 要等待put进来
                this.wait();
            }

            //取出队列的元素 就是取出队头元素
            String result = elems[head];
            head++;
            if (head >= elems.length) {
                head = 0;
            }
            size--;
            //take一个元素就要唤醒  一个
            this.notify();
            return result;
        }
    }
}



public class Demo31 {
    public static void main(String[] args) {

        //实例化一个阻塞队列
        MyBlockingQueue queue = new MyBlockingQueue(1000);

        //创建两个线程
        Thread t1 = new Thread(() -> {
            try {
                int count = 0;
                while (true) {
                    queue.put(count + "");
                    System.out.println("生产" + count);
                    count++;
                }
            }catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        //消费者
        Thread t2 = new Thread(() -> {
            try {
                while (true) {
                    String result = queue.take();
                    System.out.println("消费" + result);
                    Thread.sleep(1000);   //每秒消费一个
                }
            }catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        //启动线程
        t1.start();
        t2.start();

    }
}
